<script lang="ts" setup name="approvalInstance">
import { reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { formatDate } from '/@/utils/formatTime';

// 模拟审批流程数据
const state = reactive({
  loading: false,
  tableData: [] as any[],
  selectData: [] as any[],
  params: { page: 1, pageSize: 20 },
  filters: { 
    keyword: '', 
    status: '', 
    flowType: '',
    applicant: ''
  },
  // 我的待办
  myTasks: [] as any[],
  // 我发起的
  myInitiated: [] as any[],
  // 已处理的
  myProcessed: [] as any[],
  activeTab: 'myTasks'
});

// 审批状态选项
const statusOptions = [
  { label: '全部', value: '' },
  { label: '待审核', value: 'pending' },
  { label: '已通过', value: 'approved' },
  { label: '已驳回', value: 'rejected' },
  { label: '已撤回', value: 'withdrawn' },
  { label: '已完成', value: 'completed' }
];

// 流程类型选项
const flowTypeOptions = [
  { label: '全部', value: '' },
  { label: '进货订单审批', value: 'purchase_order' },
  { label: '销售订单审批', value: 'sales_order' },
  { label: '退货订单审批', value: 'return_order' },
  { label: '销售退货审批', value: 'sales_return_order' },
  { label: '入库单审批', value: 'in_stock_order' },
  { label: '出库单审批', value: 'out_stock_order' },
  { label: '调拨单审批', value: 'transfer_order' },
  { label: '盘点单审批', value: 'stocktaking_order' }
];

// 模拟数据
const mockData = [
  {
    id: 1,
    instanceId: 'WF202401001',
    flowType: 'purchase_order',
    flowTypeName: '进货订单审批',
    businessId: 'JHDH3848',
    businessName: 'iPhone 15 Pro进货单',
    applicant: '任杰',
    applicantId: 1300000000001,
    currentStep: '部门经理审核',
    currentApprover: '张经理',
    status: 'pending',
    statusText: '待审核',
    priority: 'high',
    createTime: '2024-01-15 09:30:00',
    updateTime: '2024-01-15 09:30:00',
    deadline: '2024-01-17 18:00:00',
    formData: {
      supplier: '供应商一',
      amount: 8000,
      goodsName: 'iPhone 15 Pro',
      quantity: 1
    },
    approvalHistory: [
      {
        step: '提交申请',
        approver: '任杰',
        result: 'submit',
        resultText: '已提交',
        time: '2024-01-15 09:30:00',
        comment: '申请采购iPhone 15 Pro'
      }
    ]
  },
  {
    id: 2,
    instanceId: 'WF202401002',
    flowType: 'sales_order',
    flowTypeName: '销售订单审批',
    businessId: 'XSDH9051',
    businessName: '华为平板销售单',
    applicant: '李销售',
    applicantId: 1300000000002,
    currentStep: '财务审核',
    currentApprover: '王财务',
    status: 'approved',
    statusText: '已通过',
    priority: 'normal',
    createTime: '2024-01-14 14:20:00',
    updateTime: '2024-01-15 10:15:00',
    deadline: '2024-01-16 18:00:00',
    formData: {
      customer: '客户一',
      amount: 2500,
      goodsName: '华为平板',
      quantity: 1
    },
    approvalHistory: [
      {
        step: '提交申请',
        approver: '李销售',
        result: 'submit',
        resultText: '已提交',
        time: '2024-01-14 14:20:00',
        comment: '销售华为平板给客户一'
      },
      {
        step: '部门经理审核',
        approver: '张经理',
        result: 'approved',
        resultText: '已通过',
        time: '2024-01-14 16:30:00',
        comment: '同意销售'
      },
      {
        step: '财务审核',
        approver: '王财务',
        result: 'approved',
        resultText: '已通过',
        time: '2024-01-15 10:15:00',
        comment: '财务审核通过'
      }
    ]
  },
  {
    id: 3,
    instanceId: 'WF202401003',
    flowType: 'return_order',
    flowTypeName: '退货订单审批',
    businessId: 'THDH1234',
    businessName: 'Nike运动鞋退货单',
    applicant: '任杰',
    applicantId: 1300000000001,
    currentStep: '质量检查',
    currentApprover: '赵质检',
    status: 'rejected',
    statusText: '已驳回',
    priority: 'normal',
    createTime: '2024-01-13 11:45:00',
    updateTime: '2024-01-14 09:20:00',
    deadline: '2024-01-15 18:00:00',
    formData: {
      supplier: '供应商二',
      reason: '质量问题',
      goodsName: 'Nike运动鞋',
      quantity: 2
    },
    approvalHistory: [
      {
        step: '提交申请',
        approver: '任杰',
        result: 'submit',
        resultText: '已提交',
        time: '2024-01-13 11:45:00',
        comment: '申请退货Nike运动鞋'
      },
      {
        step: '质量检查',
        approver: '赵质检',
        result: 'rejected',
        resultText: '已驳回',
        time: '2024-01-14 09:20:00',
        comment: '质量检查合格，不符合退货条件'
      }
    ]
  }
];

// 获取状态标签类型
const getStatusType = (status: string) => {
  const statusMap: { [key: string]: string } = {
    'pending': 'warning',
    'approved': 'success',
    'rejected': 'danger',
    'withdrawn': 'info',
    'completed': 'success'
  };
  return statusMap[status] || 'info';
};

// 获取优先级标签类型
const getPriorityType = (priority: string) => {
  const priorityMap: { [key: string]: string } = {
    'high': 'danger',
    'normal': 'info',
    'low': 'success'
  };
  return priorityMap[priority] || 'info';
};

// 获取优先级文本
const getPriorityText = (priority: string) => {
  const priorityMap: { [key: string]: string } = {
    'high': '高',
    'normal': '中',
    'low': '低'
  };
  return priorityMap[priority] || '中';
};

// 查询数据
const handleQuery = () => {
  state.loading = true;
  // 模拟API调用
  setTimeout(() => {
    let filteredData = [...mockData];
    
    // 根据当前标签页过滤数据
    if (state.activeTab === 'myTasks') {
      // 我的待办：当前审批人是当前用户且状态为pending
      // 模拟当前用户是"张经理"，所以显示待审核的任务
      filteredData = mockData.filter(item => 
        item.status === 'pending' && 
        item.currentApprover === '张经理' // 模拟当前用户是张经理
      );
    } else if (state.activeTab === 'myInitiated') {
      // 我发起的：申请人是当前用户
      // 模拟当前用户是"任杰"，所以显示任杰发起的流程
      filteredData = mockData.filter(item => 
        item.applicantId === 1300000000001 // 任杰的用户ID
      );
    } else if (state.activeTab === 'myProcessed') {
      // 已处理的：审批历史中包含当前用户
      // 模拟当前用户是"张经理"，所以显示张经理处理过的任务
      filteredData = mockData.filter(item => 
        item.approvalHistory.some(history => 
          history.approver === '张经理' && history.result !== 'submit'
        )
      );
    }
    
    // 应用筛选条件
    if (state.filters.keyword) {
      filteredData = filteredData.filter(item => 
        item.businessId.includes(state.filters.keyword) ||
        item.businessName.includes(state.filters.keyword) ||
        item.instanceId.includes(state.filters.keyword)
      );
    }
    
    if (state.filters.status) {
      filteredData = filteredData.filter(item => item.status === state.filters.status);
    }
    
    if (state.filters.flowType) {
      filteredData = filteredData.filter(item => item.flowType === state.filters.flowType);
    }
    
    state.tableData = filteredData;
    state.loading = false;
  }, 500);
};

// 发起流程
const initiateWorkflow = (businessType: string, businessId: string) => {
  ElMessageBox.confirm(`确认发起${businessType}审批流程吗？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    // 调用API发起流程
    ElMessage.success('审批流程已发起');
    handleQuery();
  }).catch(() => {});
};

// 处理审批
const handleApproval = (row: any, result: 'approved' | 'rejected') => {
  const actionText = result === 'approved' ? '通过' : '驳回';
  ElMessageBox.prompt(`请输入${actionText}意见：`, `审批${actionText}`, {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    inputType: 'textarea',
    inputPlaceholder: '请输入审批意见...',
  }).then(({ value }) => {
    const comment = value || `${actionText}审批`;
    
    // 更新审批历史
    const newHistory = {
      step: row.currentStep,
      approver: '张经理',
      result: result,
      resultText: result === 'approved' ? '已通过' : '已驳回',
      time: new Date().toLocaleString(),
      comment: comment
    };
    
    // 更新数据
    const index = mockData.findIndex(item => item.id === row.id);
    if (index !== -1) {
      mockData[index].approvalHistory.push(newHistory);
      mockData[index].updateTime = new Date().toLocaleString();
      
      if (result === 'approved') {
        // 如果通过，检查是否还有下一步
        if (row.currentStep === '部门经理审核') {
          mockData[index].currentStep = '财务审核';
          mockData[index].currentApprover = '王财务';
          mockData[index].status = 'pending';
          mockData[index].statusText = '待审核';
        } else if (row.currentStep === '财务审核') {
          mockData[index].status = 'approved';
          mockData[index].statusText = '已通过';
          mockData[index].currentStep = '已完成';
          mockData[index].currentApprover = '';
        }
      } else {
        // 驳回
        mockData[index].status = 'rejected';
        mockData[index].statusText = '已驳回';
        mockData[index].currentStep = '已驳回';
        mockData[index].currentApprover = '';
      }
    }
    
    ElMessage.success(`审批${actionText}成功`);
    handleQuery();
  }).catch(() => {});
};

// 撤回流程
const withdrawWorkflow = (row: any) => {
  ElMessageBox.confirm('确认撤回该审批流程吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    // 调用API撤回流程
    ElMessage.success('审批流程已撤回');
    handleQuery();
  }).catch(() => {});
};

// 查看详情
const viewDetail = (row: any) => {
  ElMessageBox.alert(`
    <div style="text-align: left;">
      <h3>审批流程详情</h3>
      <p><strong>流程编号：</strong>${row.instanceId}</p>
      <p><strong>业务单号：</strong>${row.businessId}</p>
      <p><strong>业务名称：</strong>${row.businessName}</p>
      <p><strong>申请人：</strong>${row.applicant}</p>
      <p><strong>当前步骤：</strong>${row.currentStep}</p>
      <p><strong>当前审批人：</strong>${row.currentApprover}</p>
      <p><strong>状态：</strong>${row.statusText}</p>
      <p><strong>优先级：</strong>${getPriorityText(row.priority)}</p>
      <p><strong>创建时间：</strong>${row.createTime}</p>
      <p><strong>更新时间：</strong>${row.updateTime}</p>
      <p><strong>截止时间：</strong>${row.deadline}</p>
      <hr>
      <h4>审批历史：</h4>
      ${row.approvalHistory.map((history: any) => `
        <div style="margin: 10px 0; padding: 10px; border: 1px solid #eee; border-radius: 4px;">
          <p><strong>步骤：</strong>${history.step}</p>
          <p><strong>审批人：</strong>${history.approver}</p>
          <p><strong>结果：</strong>${history.resultText}</p>
          <p><strong>时间：</strong>${history.time}</p>
          <p><strong>意见：</strong>${history.comment}</p>
        </div>
      `).join('')}
    </div>
  `, '审批详情', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '关闭'
  });
};

// 查看流程图
const viewFlowChart = (row: any) => {
  ElMessageBox.alert(`
    <div style="text-align: center;">
      <h3>审批流程图</h3>
      <div style="margin: 20px 0;">
        <div style="display: inline-block; margin: 10px; padding: 10px 20px; background: #e6f7ff; border: 2px solid #1890ff; border-radius: 20px;">
          提交申请
        </div>
        <div style="display: inline-block; margin: 10px;">→</div>
        <div style="display: inline-block; margin: 10px; padding: 10px 20px; background: ${row.currentStep === '部门经理审核' ? '#f6ffed' : '#f0f0f0'}; border: 2px solid ${row.currentStep === '部门经理审核' ? '#52c41a' : '#d9d9d9'}; border-radius: 20px;">
          部门经理审核
        </div>
        <div style="display: inline-block; margin: 10px;">→</div>
        <div style="display: inline-block; margin: 10px; padding: 10px 20px; background: ${row.currentStep === '财务审核' ? '#fff7e6' : '#f0f0f0'}; border: 2px solid ${row.currentStep === '财务审核' ? '#fa8c16' : '#d9d9d9'}; border-radius: 20px;">
          财务审核
        </div>
        <div style="display: inline-block; margin: 10px;">→</div>
        <div style="display: inline-block; margin: 10px; padding: 10px 20px; background: ${row.status === 'approved' ? '#f6ffed' : '#f0f0f0'}; border: 2px solid ${row.status === 'approved' ? '#52c41a' : '#d9d9d9'}; border-radius: 20px;">
          完成
        </div>
      </div>
      <p><strong>当前状态：</strong>${row.statusText}</p>
      <p><strong>当前步骤：</strong>${row.currentStep}</p>
      <p><strong>当前审批人：</strong>${row.currentApprover || '无'}</p>
    </div>
  `, '审批流程图', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '关闭'
  });
};

// 重新发起流程
const resubmitWorkflow = (row: any) => {
  ElMessageBox.prompt('请输入修改说明：', '重新发起审批流程', {
    confirmButtonText: '重新发起',
    cancelButtonText: '取消',
    inputType: 'textarea',
    inputPlaceholder: '请输入修改说明...',
  }).then(({ value }) => {
    const comment = value || '重新发起审批';
    
    // 更新数据
    const index = mockData.findIndex(item => item.id === row.id);
    if (index !== -1) {
      // 重置状态
      mockData[index].status = 'pending';
      mockData[index].statusText = '待审核';
      mockData[index].currentStep = '部门经理审核';
      mockData[index].currentApprover = '张经理';
      mockData[index].updateTime = new Date().toLocaleString();
      
      // 添加重新发起记录
      const resubmitHistory = {
        step: '重新发起',
        approver: '申请人',
        result: 'resubmit',
        resultText: '已重新发起',
        time: new Date().toLocaleString(),
        comment: comment
      };
      
      mockData[index].approvalHistory.push(resubmitHistory);
    }
    
    ElMessage.success('审批流程已重新发起');
    handleQuery();
  }).catch(() => {});
};

// 切换标签页
const handleTabChange = (tab: string) => {
  state.activeTab = tab;
  handleQuery();
};

onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="approval-instance-container">
    <!-- 标签页 -->
    <el-card shadow="hover" style="margin-bottom: 10px;">
      <el-tabs v-model="state.activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="我的待办" name="myTasks">
          <template #label>
            <span>我的待办 <el-badge :value="mockData.filter(item => item.status === 'pending' && item.currentApprover === '张经理').length" class="item" /></span>
          </template>
        </el-tab-pane>
        <el-tab-pane label="我发起的" name="myInitiated">
          <template #label>
            <span>我发起的 <el-badge :value="mockData.filter(item => item.applicantId === 1300000000001).length" class="item" /></span>
          </template>
        </el-tab-pane>
        <el-tab-pane label="已处理的" name="myProcessed">
          <template #label>
            <span>已处理的 <el-badge :value="mockData.filter(item => item.approvalHistory.some(history => history.approver === '张经理' && history.result !== 'submit')).length" class="item" /></span>
          </template>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 查询条件 -->
    <el-card shadow="hover" style="margin-bottom: 10px;">
      <el-form :inline="true">
        <el-form-item label="关键字">
          <el-input v-model="state.filters.keyword" placeholder="流程编号/业务单号/业务名称" style="width: 260px" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="state.filters.status" placeholder="全部" clearable style="width: 120px">
            <el-option v-for="opt in statusOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="流程类型">
          <el-select v-model="state.filters.flowType" placeholder="全部" clearable style="width: 160px">
            <el-option v-for="opt in flowTypeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="() => state.filters = { keyword: '', status: '', flowType: '', applicant: '' }">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="full-table" shadow="hover">
      <el-table :data="state.tableData" v-loading="state.loading" row-key="id" border>
        <el-table-column type="selection" width="40" />
        <el-table-column prop="instanceId" label="流程编号" width="140" />
        <el-table-column prop="flowTypeName" label="流程类型" width="140" />
        <el-table-column prop="businessId" label="业务单号" width="140" />
        <el-table-column prop="businessName" label="业务名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="applicant" label="申请人" width="100" />
        <el-table-column prop="currentStep" label="当前步骤" width="120" />
        <el-table-column prop="currentApprover" label="当前审批人" width="120" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ row.statusText }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="优先级" width="80">
          <template #default="{ row }">
            <el-tag :type="getPriorityType(row.priority)" size="small">
              {{ getPriorityText(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column prop="deadline" label="截止时间" width="160" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewDetail(row)">详情</el-button>
            <el-button size="small" @click="viewFlowChart(row)">流程图</el-button>
            
            <!-- 审批按钮：只有待审核状态且当前用户是审批人时才显示 -->
            <template v-if="row.status === 'pending' && row.currentApprover === '张经理'">
              <el-button type="success" size="small" @click="handleApproval(row, 'approved')">审批通过</el-button>
              <el-button type="danger" size="small" @click="handleApproval(row, 'rejected')">审批驳回</el-button>
            </template>
            
            <!-- 撤回按钮：只有我发起的且待审核状态时才显示 -->
            <template v-if="state.activeTab === 'myInitiated' && row.status === 'pending'">
              <el-button type="warning" size="small" @click="withdrawWorkflow(row)">撤回</el-button>
            </template>
            
            <!-- 重新发起按钮：已驳回状态时显示 -->
            <template v-if="row.status === 'rejected'">
              <el-button type="primary" size="small" @click="resubmitWorkflow(row)">重新发起</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<style scoped>
.approval-instance-container {
  padding: 10px;
}

:deep(.el-badge__content) {
  font-size: 12px;
}
</style>
